package com.zcoj.wx.service.impl;

import com.zcoj.util.RedisCaches;
import com.zcoj.wx.pojo.WxQrCode;
import com.zcoj.wx.service.WxQrCodeService;
import com.zcoj.wx.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author chenbin
 * @version 1.0
 * @description: TODO
 * @date 2023/8/19 09:09
 */
@Slf4j
@Service
public class WxSendTemplateMsgImpl {

    // @Value("#{wxProperties.wx_template_id}")
    private final String WX_TEMPLATE_ID_1="YwTn-SvknQQeoQ_TkESWmTAH_xxX6txlbwjmQibq0w0";

    //6ckHAPkYka0o47uaFs7jC-Rnr0v6eLbQr0yJl5_v6bY
    private final String WX_TEMPLATE_ERROE_MESSAGE_ID="6ckHAPkYka0o47uaFs7jC-Rnr0v6eLbQr0yJl5_v6bY";

    private final String WX_TEMPLATE_SUCCESS_MESSAGE_ID="D54qKPcg7YS3i0Qeov2LNZsSz-yCs618Uog96-KCq3k";

    private final String SCAN_LOGIN="1";

    private final String SCAN_BIND="2";

    private final String SUB_SCRIBE_LOGIN="qrscene_"+SCAN_LOGIN;

    private final String SUB_SCRIBE_BIND="qrscene_"+SCAN_BIND;

    @Autowired
    private RedisCaches redisCaches;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private WxQrCodeService wxQrCodeService;

    private WxMpService wxMpService;

    public void SetWxMpService(WxMpService wxMpService){
        this.wxMpService=wxMpService;
    }

    public String checkMsgType(Map<String,Object> allFieldsMap){
        log.info("{}",allFieldsMap);
        String event = (String) allFieldsMap.get("Event");
        String  fromUserName = (String) allFieldsMap.get("FromUserName");
        String eventKey = (String) allFieldsMap.get("EventKey");
        if (eventKey.equals(SCAN_LOGIN)||eventKey.equals(SUB_SCRIBE_LOGIN)||eventKey.equals(SUB_SCRIBE_BIND)||eventKey.equals(SCAN_BIND)){
            String ticket = (String) allFieldsMap.get("Ticket");
            //检测图片ticket 是否合法
            WxQrCode wxQrCode = wxQrCodeService.getWxQrCodeByTicket(ticket);
            if ( Objects.isNull(wxQrCode)){
                wxQrCode=new WxQrCode();
                wxQrCode.setEventKey(eventKey);
                wxQrCode.setTicket(ticket);
                wxQrCode.setIsUsed(1);
                wxQrCode.setIsPass(0);
                wxQrCode.setOpenId(fromUserName);
                wxQrCode.setIsExpire(1);
                wxQrCode.setEvent(event);
                wxQrCodeService.insertWxQrCode(wxQrCode);
                // TODO: 推送失败模版消息
                return errorMsgTemplate(fromUserName,eventKey,"二维码参数异常");
            }else {
                wxQrCode.setIsUsed(1);
                if((Objects.nonNull(wxQrCode.getIsExpire())&&wxQrCode.getIsExpire()==1)){
                    wxQrCode.setEventKey(eventKey);
                    wxQrCode.setIsPass(0);
                    wxQrCode.setTicket(ticket);
                    wxQrCode.setOpenId(fromUserName);
                    wxQrCode.setEvent(event);
                    wxQrCodeService.updateWxQrCode(wxQrCode);
                   // TODO: 推送被使用消息
                    return errorMsgTemplate(fromUserName,eventKey,"二维码已失效");

                }else {
                    Date date = new Date();
                    Date expireTime = wxQrCode.getExpireTime();
                    if(expireTime.getTime()<date.getTime()){
                        wxQrCode.setEventKey(eventKey);
                        wxQrCode.setTicket(ticket);
                        wxQrCode.setIsPass(0);
                        wxQrCode.setOpenId(fromUserName);
                        wxQrCode.setIsExpire(1);
                        wxQrCode.setEvent(event);
                        wxQrCodeService.updateWxQrCode(wxQrCode);
                        // TODO: 推送二维码过期消息
                        return errorMsgTemplate(fromUserName,eventKey,"二维码已失效");

                    }else {
                        //通过wx校验 ->进入用户绑定校验
                        Integer integer = wxUserService.checkWxOpenId(fromUserName);
                        if (eventKey.equals(SUB_SCRIBE_LOGIN)||eventKey.equals(SCAN_LOGIN)){
                            wxQrCode.setEventKey(eventKey);
                            wxQrCode.setTicket(ticket);
                            wxQrCode.setOpenId(fromUserName);
                            wxQrCode.setIsExpire(0);
                            wxQrCode.setEvent(event);
                            if (integer.equals(0)){
                                //系统账号未绑定
                                wxQrCode.setIsPass(0);
                                wxQrCodeService.updateWxQrCode(wxQrCode);
                                // TODO: 返回未绑定模版
                                return errorMsgTemplate(fromUserName,eventKey,"账号未绑定请绑定后扫码");
                            }else {
                                wxQrCode.setIsPass(1);
                                wxQrCodeService.updateWxQrCode(wxQrCode);
                                return successMsgTemplate(fromUserName,eventKey,"扫码登录成功,请等待浏览器响应");
                            }
                        }else {
                            //bing
                            wxQrCode.setEventKey(eventKey);
                            wxQrCode.setTicket(ticket);
                            wxQrCode.setOpenId(fromUserName);
                            wxQrCode.setIsExpire(0);
                            wxQrCode.setEvent(event);
                            if (integer.equals(0)){
                                wxQrCode.setIsPass(1);
                                wxQrCodeService.updateWxQrCode(wxQrCode);
                                return successMsgTemplate(fromUserName,eventKey,"扫码绑定成功,请等待浏览器响应");
                            }else {
                                //系统账号未绑定
                                wxQrCode.setIsPass(0);
                                wxQrCodeService.updateWxQrCode(wxQrCode);
                                // TODO: 返回未绑定模版
                                return errorMsgTemplate(fromUserName,eventKey,"账号已绑定其他用户");
                            }
                        }
                    }
                }
            }

        }
//        else {
//
//            return manuscriptExamine(fromUserName);
//        }
        return null;
    }


    //案例： 星巴克支付通知
    public String manuscriptExamine(String openId) {

        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId(WX_TEMPLATE_ID_1);
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser(openId);
        //构建消息格式
        List<WxMpTemplateData> listData = Arrays.asList(
            new WxMpTemplateData("first", "恭喜你支付成功！", "#173177"),
            new WxMpTemplateData("keyword1", "曹.", "#173177"),
            new WxMpTemplateData("keyword2", "2019698571200", "#173177"),
            new WxMpTemplateData("keyword3", "￥98.80", "#173177"),
            new WxMpTemplateData("keyword4", "星冰乐（焦糖味） 家乐氏香甜玉米片*2 乐天七彩爱情糖*3", "#173177"),
            new WxMpTemplateData("remark", "如有疑问，请联系客服电话：021-54145323", "#173177")
        );
        //接收发送模板消息结果,就是msgid，if(msgid! = null)即成功
        String wxTemplateResult = null;
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(listData);
        try {
            //发送模板
            wxTemplateResult = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            log.error("发送模板消息异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return wxTemplateResult;
    }

    public String errorMsgTemplate(String openId,String type,String msg) {
        /*
             {{first.DATA}}
            操作：{{keyword1.DATA}}
            描述：{{keyword2.DATA}}
         **/
        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId(WX_TEMPLATE_ERROE_MESSAGE_ID);
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser(openId);
        //构建消息格式
        List<WxMpTemplateData> listData = Arrays.asList(
                new WxMpTemplateData("first", "操作失败", "#173177"),
                new WxMpTemplateData("keyword1", type.equals(SCAN_LOGIN)?"扫码登录":"账号绑定", "#173177"),
                new WxMpTemplateData("keyword2", msg, "#173177")
        );
        //接收发送模板消息结果,就是msgid，if(msgid! = null)即成功
        String wxTemplateResult = null;
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(listData);
        try {
            //发送模板
            wxTemplateResult = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            log.error("发送模板消息异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return wxTemplateResult;
    }

    public String successMsgTemplate(String openId,String type,String msg) {
        /*
             {{first.DATA}}
            操作：{{keyword1.DATA}}
            描述：{{keyword2.DATA}}
         **/
        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId(WX_TEMPLATE_SUCCESS_MESSAGE_ID);
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser(openId);
        //构建消息格式
        List<WxMpTemplateData> listData = Arrays.asList(
                new WxMpTemplateData("first", "操作成功", "#173177"),
                new WxMpTemplateData("keyword1", type.equals(SCAN_LOGIN)?"扫码登录":"账号绑定", "#173177"),
                new WxMpTemplateData("keyword2", msg, "#173177")
        );
        //接收发送模板消息结果,就是msgid，if(msgid! = null)即成功
        String wxTemplateResult = null;
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(listData);
        try {
            //发送模板
            wxTemplateResult = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            log.error("发送模板消息异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return wxTemplateResult;
    }
}
